package timu2;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class XmlDUS {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        File file=new File("D://java作业/Fuxi/XML.xml");
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document doc = documentBuilder.parse(file);

        //增
        Element person = doc.createElement("person");
        person.setAttribute("id","3");
        Element name = doc.createElement("name");
        name.appendChild(doc.createTextNode("王五"));
        Element age = doc.createElement("age");
        age.appendChild(doc.createTextNode("22"));
        Element address = doc.createElement("address");
        address.appendChild(doc.createTextNode("天津"));
        Element gender = doc.createElement("gender");
        gender.appendChild(doc.createTextNode("男"));
        person.appendChild(name);
        person.appendChild(address);
        person.appendChild(age);
        person.appendChild(gender);
        doc.getDocumentElement().appendChild(person);




        //改
        NodeList person1 = doc.getElementsByTagName("person");
        Node first = person1.item(0);
        ((Element)first).getElementsByTagName("age").item(0).setTextContent("1000");




//        //删
//        if (person1.getLength()>1){
//            doc.getDocumentElement().removeChild(person1.item(1));
//        }


        //查
        NodeList list=doc.getElementsByTagName("person");
        for (int i=0;i<list.getLength();i++){
            Node titleNode=list.item(i);
            if (titleNode.getNodeType()==Node.ELEMENT_NODE){
                Element element= (Element) titleNode;
                System.out.println(element.getTextContent());
            }
        }


        //保存文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        DOMSource source=new DOMSource(doc);
        StreamResult result=new StreamResult(new FileWriter("newXml.xml"));
        transformer.transform(source,result);
    }
}
